from models.models.RequestResult import RequestResult as Res
from django.views.decorators.csrf import csrf_exempt
from django.core import serializers
from models.models.CustomerReply import CustomerReply
from django.http.response import JsonResponse
from django.shortcuts import render
import json
import math


# 获取菜单列表
def get_menu_list(request):
    page_number = request.GET.get("page_number")
    if page_number is None:
        page_number = 1
    else:
        page_number = int(page_number)
    page_size = 10
    limit = (page_number - 1) * page_size
    offset = limit+page_size
    count = 0
    feedbacks = []
    back_user_id = request.GET.get("back_user_id")
    if not back_user_id:
        feedbacks = CustomerReply.objects.filter().order_by("-id")[limit:offset]
        count = CustomerReply.objects.filter().count()
    else:
        feedbacks = CustomerReply.objects.filter(back_user_id__contains=back_user_id).order_by("-id")[limit:offset]
        count = CustomerReply.objects.filter(menu_name__contains=menu_name).count()
    page_total = math.ceil(count / page_size)
    res_feedbacks = []
    for feedback in feedbacks:
        res_feedback = dict()
        res_feedback["id"] = feedback.id
        res_feedback["keyword"] = feedback.keyword
        res_feedback["reply"] = feedback.reply
        res_feedbacks.append(res_feedback)
    res_date = dict()
    res_date["list"] = res_feedbacks
    res_date["page_number"] = page_number
    res_date["page_total"] = page_total
    return JsonResponse(Res.success(res_date))


# 转发到商城菜单管理页
def to_menu(request):
    fields = CustomerReply.get_fields()
    res = {
        "name": "意见反馈",
        "fields": fields,
        "getListUrl": "/admin/customer/reply/getList/",
        "getOneUrl": "/admin/customer/reply/getOne/",
        "insertUrl": "/admin/customer/reply/insert/",
        "updateUrl": "/admin/customer/reply/update/",
        "deleteUrl": "/admin/customer/reply/delete/"
    }
    return render(request, "storeAdmin/common/list.html", res)


# 获取某一菜单
def get_menu_one(request):
    id = request.GET.get('id')
    feedback = CustomerReply.objects.filter(id=id).first()
    return JsonResponse(feedback.to_dict())

# 新增菜单
@csrf_exempt
def insert(request):
    feedback = CustomerReply()
    feedback.keyword = request.POST.get("keyword")
    feedback.reply = request.POST.get("reply")
    feedback.save()
    return JsonResponse(Res.success(None))


# 更新菜单
@csrf_exempt
def update(request):
    feedback = CustomerReply.objects.get(id=request.POST.get("id"))
    feedback.keyword = request.POST.get("keyword")
    feedback.reply = request.POST.get("reply")
    feedback.save()
    return JsonResponse(Res.success(None))


# 删除菜单
def delete(request):
    id = request.GET.get("id")
    feedback = CustomerReply.objects.filter(id=id).first()
    feedback.delete()
    return JsonResponse(Res.success(None))
